// curl -k5/wx/login
const http = require('http');
const https = require('https');

//雪花算法生成
const Snowflake = require('./snowflack')

const SQLHelper = require('./SQLHepler')
const {formatTime}=require('./util')


module.exports = function (app) {

  function loginRouter(req, res, next) {
    //登录拦截中间件
    let token = req.headers.token

    if (token) {
      SQLHelper(`select * from session where id=${token}`).then(ret => {
        if (ret.length) {
          let session = ret[0]
          req.session = {
            userId: session.userId,
            userName: session.userName
          }
          next()
        } else {
          res.status(406).send({ errorMsg: '当前用户未登录' })
        }
      })
    }
    else {
      res.status(405).send({ errorMsg: '缺少token,请先登录' })
    }

  }

  //让初登录的所有小程序接口先验证登录
  app.use('/wx', loginRouter)


  //微信登录
  app.get('/wxlogin', (req, res, next) => {
    console.log(req.headers)
    let code = req.query.code
    let appid = 'wx55af8c69f69bff10'
    let secret = '28fc1e9dfb065c3e2d843aded9f5fc7e'

    https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {

      ret.on('data', (ret) => {
        ret = JSON.parse(ret.toString())
        let openid = ret.openid
        if (!openid) {
          res.send({ errorMsg: ret.errorMsg || '获取openid错误' })
        }
        else {//查询用户是否注册

          let queryMember = `select * from member where openId='${openid}'`
          SQLHelper(queryMember).then(membersRet => {
            console.log(membersRet)
            if (membersRet.length) {//用户存在
              //挂载到req
              req.member = membersRet[0]
              next()

            }
            else {//用户不存在，注册
              SQLHelper(`INSERT INTO member (openId)  VALUES ('${openid}')`).then(newMember => {
                SQLHelper(queryMember).then(newMember => {
                  //挂载到req
                  req.member = membersRet[0]
                  next()
                })

              })
            }
          })
        }
      });

    }).on('error', (e) => {
      console.error(e);
      res.send('获取openId错误')
    }
    );

  }, (req, res) => {
    let token = Snowflake()
    let member = req.member
    //缓存到tokens 到session表

    SQLHelper(`
  INSERT INTO session (id,userId,userName,inTime,platform)  VALUES 
  (${token},'${member._id}','${member.nickName}','${formatTime(new Date())}','wx')
  `).then(ret => {
      res.send({
        nickName: member.nickName,
        token,
        openid: member.openid,
        avatarUrl: member.avatarUrl,
        _id: member._id
      })
    })
  })

  //修改用户信息
  app.put('/wx/member', (req, res) => {
    let userInfo = req.body
    console.log(userInfo, req.query)
    SQLHelper(`update member set nickName= '${userInfo.nickName}',avatarUrl='${userInfo.avatarUrl}' 
  where _id='${req.session.userId}'
  `).then(ret => {
      console.log(ret)
      res.send({})

    })

  })

  //获取收货地址列表
  //memberId 用户ID必填
  app.get('/wx/address', (req, res) => {

    if (req.session.userId) {
      SQLHelper(`
    select * from address where state =1 and memberId ='${req.session.userId}'
    `).then(ret => {
        res.send(ret)
      })
    }
    else {
      res.send({ errorMsg: '请传入memberId' })
    }

  })

  //获取收货地址详情
  //memberId 用户ID必填
  app.get('/wx/address/detail', (req, res) => {

    if (req.query.addressId) {
      SQLHelper(`
    select * from address where _id='${req.query.addressId}'
    `).then(ret => {
        res.send(ret.length ? ret[0] : { errorMsg: '未获取到地址详情' })
      })
    }
    else {
      res.send({ errorMsg: '请传入addressId' })
    }

  })

  //新增收货地址
  //memberId用户ID  receiver收货人 phone手机号 city省市区必填
  app.post('/wx/address', (req, res) => {

    if (req.body.memberId && req.body.receiver && req.body.phone && req.body.city) {
      SQLHelper(`
    INSERT INTO address (state,memberId,receiver,phone,city,area)  VALUES 
    (1,'${req.session.userId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || ' '}')
    `).then(ret => {
        res.send(ret)
      })
    }
    else {
      res.send({ errorMsg: '请求参数错误' })
    }

  })

  //修改收货地址
  //addressId地址_id    非 receiver收货人 phone手机号 city省市区必填 area
  app.put('/wx/address', (req, res) => {

    if (req.body.addressId) {
      let updatekey = ['receiver', 'phone', 'city', 'area']
      let updateValues = []

      for (let i = 0; i < updatekey.length; i++) {
        let key = updatekey[i], value = req.body[key]
        if (value) updateValues.push(`${key}='${value}'`)

      }

      SQLHelper(`
    update address set ${updateValues.join(',')} where _id = ${req.body.addressId}
    `).then(ret => {
        res.send(ret)
      })
    }
    else {
      res.send({ errorMsg: '传入参数错误' })
    }

  })

  //修改为默认地址
  //addressId 主码_id必填
  //memberId
  app.put('/wx/address/default', (req, res) => {
    let addressId = req.body.addressId, isDefault = req.body.isDefault == 1 ? 1 : 0, memberId = req.session.userId
    if (addressId && memberId) {
      if (isDefault == 1) {//设置默认地址
        //取消其他默认地址
        SQLHelper(`
      UPDATE address SET isDefault =0  where isDefault=1 and memberId='${memberId}'
      `).then(ret => {
          SQLHelper(`
        UPDATE address SET isDefault =1  where _id='${addressId}'
        `).then(ret => {
            res.send(ret)
          })

        })
      }
      else {
        //取消默认地址
        SQLHelper(`
        UPDATE address SET isDefault =0  where _id='${addressId}'
        `).then(ret => {
          res.send(ret)
        })
      }
    }

    else {
      res.send({ errorMsg: '请求参数错误' })
    }
  })


  //删除地址 逻辑
  app.delete('/wx/address', (req, res) => {
    let addressId = req.body.addressId
    if (addressId) {
      SQLHelper(`
    UPDATE address SET state =0  where _id='${addressId}'
    `).then(ret => {
        res.send(ret)
      })
    }

    else {
      res.send({ errorMsg: '请求参数错误' })
    }
  })
}

